<?php

/*
 * @Descripttion: 
 * @version: v1
 * @Author: 
 * @Date: 2022-02-15
 */

declare(strict_types=1);

namespace app\video\controller\admin\v1;

use think\Request;
use think\facade\Db;

class Type
{
    /**
     * @Descripttion:获取类别
     * @Author: 
     * @Date: 2022-02-15
     * @param {*}
     */
    public function getList(Request $request)
    {
        $data = $request->data;
        $limit =  $data['limit'] ?? 10;
        $page = $data['page'];
        $offset = ($page - 1) * $limit;
        $where = [
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],
        ];

        if (!empty($data['name'])) array_push($where, ['name', 'like', '%' . $data['name'] . '%']);

        $list = DB::table('video_type')
            ->where($where)
            ->field(['name', 'uuid', 'remark'])
            ->limit((int)$offset, (int)$limit)
            ->order('id', 'DESC')
            ->select()->toArray();

        $count = DB::table('video_type')
            ->where($where)
            ->count();
        $data = [
            'list' => $list,
            'count' => $count,
        ];

        return result(SUCCESS, $data, '');
    }

    public function create(Request $request)
    {
        $data = $request->data;
        $data['uuid'] = createUuid();
        $data['projectCode'] = $request->prjCode;
        $data = dataMerge('', $data);
        DB::startTrans();
        try {
            DB::table('video_type')->insert($data);
            DB::commit();
            return result(SUCCESS, $data['uuid'], '添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }
        return result(FAIL, '', '添加失败');
    }


    public function update(Request $request)
    {
        $data = $request->data;
        $where = [
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],
        ];
        $nameCheck = DB::table('video_type')
            ->where(['name' => $data['name'], 'isDelete' => 0])
            ->value('uuid');

        if ($nameCheck && $data['uuid'] != $nameCheck) return result(FAIL, '', '名称重复，请重新输入');
        $where[2] =
            ['uuid', '=', $data['uuid']];
        $data = [
            'name' => $data['name'],
            'remark' => $data['remark'],
        ];
        $checkData = DB::table('video_type')->where($where)->update($data);
        if ($checkData) return result(SUCCESS, '', '更新成功');
        return result(FAIL, '', '更新失败');
    }


    public function destroy(Request $request)
    {
        $data = $request->data;
        $where = [
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],
            ['uuid', '=', $data['uuid']],
        ];
        $checkData = DB::table('video_type')->where($where)->update(['isDelete' => 1]);
        if ($checkData) return result(SUCCESS, '', '删除成功');
        return result(FAIL, '', '删除失败');
    }

    /**
     * @Descripttion:已绑定摄像头列表
     * @Author: 
     * @Date: 2022-02-15
     * @param {*}
     */
    public function getCameraList(Request $request)
    {
        $data = $request->data;
        $limit =  $data['limit'] ?? 10;
        $page = $data['page'];
        $offset = ($page - 1) * $limit;
        $where = [
            ['tc.isDelete', '=', 0],
            ['tc.projectCode', '=', $request->prjCode],
            ['tc.typeUuid', '=', $data['typeUuid']]
        ];

        if (!empty($data['name'])) array_push($where, ['c.name', 'like', '%' . $data['name'] . '%']);

        $list = DB::table('video_typeCamera')->alias('tc')
            ->join('video_projectCamera c', 'tc.cameraUuid=c.uuid')
            ->where($where)
            ->field(['c.uuid as cameraUuid', 'c.number', 'c.uuid', 'c.name', 'c.connection','tc.typeUuid'])
            ->limit((int)$offset, (int)$limit)
            ->order('tc.id', 'DESC')
            ->select()->toArray();

        $count = DB::table('video_typeCamera')->alias('tc')
            ->join('video_projectCamera c', 'tc.cameraUuid=c.uuid')
            ->where($where)
            ->count();
        $data = [
            'list' => $list,
            'count' => $count,
        ];

        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 绑定设备头
     * @param {Request} $request
     */
    public function bindCamera(Request $request)
    {
        $data = $request->data;
        $typeUuid = $data['uuid'];
        $cameraUuids = $data['cameraUuid'];
        $globalData = dataMerge($request->uuid, [
            'typeUuid' => $typeUuid,
            'projectCode' => $request->prjCode,
        ]);

        DB::startTrans();
        try {
            DB::table('video_typeCamera')
                ->where([
                    'typeUuid' => $typeUuid,
                ])
                ->delete();
            if ($cameraUuids) {
                foreach ($cameraUuids as $value) {
                    $insertData[] = array_merge(['uuid' => createUuid(), 'cameraUuid' => $value], $globalData);
                }
                DB::table('video_typeCamera')->insertAll($insertData);
            }
            DB::commit();
            return result(SUCCESS, '', '绑定摄像头成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '绑定摄像头失败');
        }
    }
    /**
     * @Description: 删除绑定摄像头
     * @param {Request} $request
     */
    public function unbindCamera(Request $request)
    {
        $data = $request->data;
        $where = [
            ['isDelete', '=', 0],
            ['typeUuid', '=', $data['typeUuid']],
            ['cameraUuid', '=', $data['uuid']],
        ];
        $checkData = DB::table('video_typeCamera')->where($where)->update(['isDelete' => 1]);
        if ($checkData) return result(SUCCESS, '', '删除绑定摄像头成功');
        return result(FAIL, '', '删除绑定摄像头失败');
    }

    /**
     * @Description: 获取绑定摄像头穿梭框字典
     * @param {Request} $request
     */
    public function getBindList(Request $request)
    {
        $data = $request->data;
        $where = [
            ['pc.projectCode', '=', $request->prjCode],
            ['pc.isDelete', '=', 0],
        ];
        $lists = DB::table('video_projectCamera')->alias('pc')
            ->join('video_typeCamera tc', 'pc.uuid=tc.cameraUuid', 'left')
            ->where($where)
            ->where($request->authWhere)
            ->field(['pc.id','pc.name as label', 'pc.uuid as value', 'pc.pid', 'tc.typeUuid'])
            ->group('pc.id')
            ->select()->toArray();
        $lists = array_map(function ($item) use($data) {
            if ($item['typeUuid'] && $data['uuid'] != $item['typeUuid']) {
                $item['disabled'] = 1;
            } else {
                $item['disabled'] = 0;
            }
            unset($item['typeUuid']);
            return $item;
        }, $lists);
        $lists = $this->buildTree($lists);
        $value = DB::table('video_typeCamera')
            ->where(['typeUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('cameraUuid');
        $data = compact('lists', 'value');

        return result(SUCCESS, $data, '');
    }

    public function buildTree($list, $pid = 0)
    {
        $branch = [];
        foreach ($list as $item) {
            if ($item['pid'] == $pid) {
                $children = $this->buildTree($list, $item['id']);
                if ($children) {
                    $item['children'] = $children;
                }
                $branch[] = $item;
            }
        }
       
        return $branch;
    }
}
